<script>
import jwtDecode from 'jwt-decode';
import md5 from 'js-md5';
import userManager from '@/common/manager/user-manager.js';
import request from '@/common/request/api.js';
import { mapMutations } from 'vuex';

import { getScene, getSceneQuery, temporaryToken } from '@/common/utils.js';

export default {
    globalData: {
        deviceType: uni.getSystemInfoSync().platform || null,
        isSafeAreaInsetBottom: false, // 是否支持safe-area-inset-bottom属性
        isDevicePad: false, // 是否平板
        userInfo: uni.getStorageSync('token') ? jwtDecode(uni.getStorageSync('token')).data : undefined,
        collegeCollects: [], // 学校收藏列表
        majorCollects: [], // 专业收藏列表
        jobCollects: [], // 职业收藏列表
        newsCollects: [], // 文章收藏列表
        collegeContrasts: [], // 学校对比列表
        poparr: [], //弹框数组渲染的数据  一维数组
        opendata: false, //弹框控制开关
        selecttext: '1', //初次匹配的文字
        arrtext: '1', //数组的标题
        shequflag: 1, //社区广告
        joblog: true,
        typeIos: false, // 设置机型
        banbengengxin: '0', //0是不更新  1是更新
        batchPickers: [] // 批次线数据，
    },
    methods: {
        objectToQueryString(obj) {
            return Object.entries(obj)
                .map(([key, value]) => `${key}=${value}`)
                .join('&');
        },
        ...mapMutations(['SET_UPDATE_APP']),
        getshare() {
            uni.getClipboardData({
                success: function (res) {
                    try {
                        let obj = JSON.parse(res.data);
                        if (obj.visitorId) {
                            request.invitedNew(obj).then((res) => {
                                uni.setStorageSync('visitorId', obj);
                            });
                        }
                    } catch (e) {}

                    uni.hideToast();
                },
                fail: (res) => {}
            });
            uni.hideToast();
        },
        getUserCollect() {
            if (this.globalData.userInfo) {
                this.$request.likeList().then((res) => {
                    this.globalData.collegeCollects = res.data['school'].split(',');
                    this.globalData.majorCollects = res.data['major'].split(',');
                    this.globalData.jobCollects = res.data['job'].split(',');
                    this.globalData.newsCollects = res.data['news'].split(',');
                    this.globalData.collegeContrasts =
                        res.data['compare'].length > 0 ? res.data['compare'].split(',') : [];
                });
            }
        },
        // 安装wgt包
        installWgt(path) {
            let _this = this;
            plus.runtime.install(
                path,
                {
                    force: false
                },
                () => {
                    plus.runtime.restart();
                },
                (err) => {
                    uni.hideLoading();
                    uni.showModal({
                        title: '更新失败',
                        content: err.message,
                        showCancel: false
                    });
                    this.globalData.banbengengxin = 1;
                    _this.SET_UPDATE_APP(false);
                }
            );
        },
        /**
         * @description 每两秒定时监听同意隐私政策
         */
        watchArgeeStatic(count = 10) {
            uni.onPushMessage((res) => {
                if (res.type == 'receive') {
                    uni.createPushMessage({
                        content: '消息推送成功'
                    });
                }
                //1
                if (res.type == 'click') {
                    let data = {};
                    if (res.data.payload.id) {
                        data.id = res.data.payload.id;
                    }
                    if (res.data.payload.nid) {
                        data.nid = res.data.payload.nid;
                    }
                    this.$request.schoolNewsDetail(data).then((res) => {
                        if (data.id) {
                            res.data.id = data.id;
                        }
                        if (data.nid) {
                            res.data.nid = data.nid;
                        }
                        uni.navigateTo({
                            url:
                                '/subpackages/subpackage1/pages/searchcollege/collegeDetails/news-details?data=' +
                                encodeURIComponent(JSON.stringify(res.data))
                        });
                    });
                }
            });
        },

        // 获取sass配置信息
        platformInfo() {
            this.$request
                .getPlatformInfo()
                .then((res) => {
                    if (res.code == 20000) {
                        let infoString = JSON.stringify(res.data);
                        uni.setStorageSync('storeInfo', infoString);
                    } else {
                        console.error('接口返回错误:', res.message);
                        this.againGetPlatformInfo();
                    }
                })
                .catch((err) => {
                    console.error('请求错误:', err);
                    this.againGetPlatformInfo();
                });
        },
        againGetPlatformInfo() {
            // 设置一个延时，以避免迅速重复调用
            setTimeout(() => {
                console.log('再次尝试获取平台信息...');
                this.PlatformInfo(); // 递归调用
            }, 2000); // 这里设置2秒延迟
        },

        // 获取用户协议隐私政策
        privacyPolicy() {
            this.$request.getPrivacyPolicy().then((res) => {
                uni.setStorageSync('userAgreement', res.data.data);
                uni.setStorageSync('privacyPolicy', res.data.templateData);
            });
        }
    },
    onLaunch: async function (val) {
        //第一次进入页面判断有误token 如果有token 代表是正式用户 否则是临时用户此时纯token 存场景值 存用户信息
        let scene = getScene();
        uni.setStorageSync('scene', scene);
        if (!uni.getStorageSync('token')) {
            if ([1007, 1008].includes(scene)) {
                let token = await temporaryToken('token');
                const userInfo = jwtDecode(token).data;
                uni.setStorageSync('token', token);
                uni.setStorageSync('is_visitor', userInfo.is_visitor);
                getApp().globalData.userInfo = userInfo;

                // 保证本地一定有token才跳转
                let queryString = this.objectToQueryString(val.query);
                console.log(queryString, 'url拼接');
                if (uni.getStorageSync('token')) {
                    uni.reLaunch({
                        url: `/${val.path}?${queryString}`
                    });
                }
            } else {
                uni.removeStorageSync('scene');
                uni.removeStorageSync('is_visitor');
            }
        } else {
            if ([1007, 1008].includes(scene)) {
                let queryString = this.objectToQueryString(val.query);
                if (uni.getStorageSync('token')) {
                    uni.reLaunch({
                        url: `/${val.path}?${queryString}`
                    });
                }
            }
        }
        // ================================

        uni.onAppRoute((res) => {
            if (res.openType == 'switchTab') {
                let flag = ['pages/tabBar/ping/ping', 'pages/tabBar/wode/vip-details-copy'].includes(res.path);
                if (uni.getStorageSync('is_visitor') == 1 && flag) {
                    uni.reLaunch({
                        url: '/pages/login/login-home?from=1'
                    });
                }
            }
        });

        this.platformInfo();
        this.privacyPolicy();
        this.globalData.typeIos = uni.getSystemInfoSync().platform == 'ios';
        this.globalData.isSafeAreaInsetBottom = uni.canIUse('safe-area-inset-bottom');
        // 隐私政策同意后才能初始化推送消息
        this.watchArgeeStatic();
        if (val.query.token) {
            uni.setStorageSync('token', val.query.token);
        }
        request.judgeQuestionDescAPI().then((res) => {
            uni.setStorageSync('questionDesc', res.data);
        });
        // 监听收藏变化
        uni.$on('handleCollectChange', () => {
            this.getUserCollect();
        });
        this.getUserCollect();

        this.getshare();

        const systemInfo = uni.getSystemInfoSync();
        const isTablet = systemInfo.screenWidth / systemInfo.pixelRatio >= 250;

        //  判断是否平板
        this.globalData.isDevicePad = isTablet;

        // 版本更新
        //#ifdef APP-PLUS
        plus.runtime.getProperty(plus.runtime.appid, (info) => {
            this.$request
                .checkVersion({
                    platform: 'IOS',
                    version: info.version,
                    type: '1' // 类型 1： 线下/测试 2： 线上/正式
                })
                .then((res) => {
                    // 热更新
                    if (res.data.url) {
                        // 进行修改参数 首页获取 操作触发回调
                        this.globalData.banbengengxin = 1;
                        const _this = this;
                        uni.$once('banbengengxingFUN', function () {
                            this.globalData.banbengengxin = 0;

                            const downloadTask = uni.downloadFile({
                                url: res.data.url,
                                success: (downloadResult) => {
                                    if (downloadResult.statusCode === 200) {
                                        uni.getFileInfo({
                                            filePath: downloadResult.tempFilePath,
                                            success(info) {
                                                let digest = info.digest.toUpperCase();
                                                digest = md5(digest);
                                                if (digest == res.data['md5']) {
                                                    _this.installWgt(downloadResult.tempFilePath);
                                                    // plus.runtime
                                                    // 	.restart()
                                                } else {
                                                    uni.showToast({
                                                        title: '文件校验失败',
                                                        icon: 'error'
                                                    });
                                                    this.globalData.banbengengxin = 1;
                                                    _this.SET_UPDATE_APP(false);
                                                }
                                            },
                                            fail(err) {
                                                // toast
                                                uni.showToast({
                                                    title: '下载失败，请稍后重试',
                                                    icon: 'none'
                                                });
                                                this.globalData.banbengengxin = 1;
                                                _this.SET_UPDATE_APP(false);
                                            }
                                        });
                                    } else {
                                        uni.showToast({
                                            title: '下载失败，请稍后重试！',
                                            icon: 'none'
                                        });
                                        _this.SET_UPDATE_APP(false);
                                    }
                                },
                                fail(err) {
                                    uni.showToast({
                                        title: '下载失败，请稍后重试！',
                                        icon: 'none'
                                    });
                                    _this.SET_UPDATE_APP(false);
                                }
                            });
                            downloadTask.onProgressUpdate((res) => {
                                uni.$emit('jdt_number', res.progress);
                            });
                        });
                    } else {
                        // Toast
                    }
                });
        });
        //#endif
    },
    onShow: async function (val) {},
    onHide: function () {}
};
</script>

<style lang="scss">
@import '@/uni_modules/uview-plus/index.scss';
/**
	 * 处理v-html里表格第三行时间换行的问题
	 */
.container tr td:nth-child(3) {
    /* 样式属性 */
    min-width: 3rem !important;
}

/**
	 * 隐藏scroll-view的滚动条
	 */
::-webkit-scrollbar {
    display: none;
    width: 0;
    height: 0;
    color: transparent;
}

body {
    height: 100%;
}

page {
    height: 100%;
}

/*每个页面公共css */
.background-color-F8F8F8 {
    background-color: #f8f8f8;
}

.background-color-FFF {
    background-color: #fff;
}

.flex-row {
    display: flex;
    flex-direction: row;
}

.flex-column {
    display: flex;
    flex-direction: column;
}

.flex-wrap {
    flex-wrap: wrap;
}

.center-row {
    align-items: center;
}

.center-column {
    justify-content: center;
}

.space-between {
    justify-content: space-between;
}

.space-around {
    justify-content: space-around;
}

.enT {
    font-family: AlimamaShuHeiTi, AlimamaShuHeiTi;
    font-weight: bold;
    font-size: 36rpx;
    color: #ff3b0a;
    line-height: 36rpx;
    letter-spacing: 4rpx;
    font-style: normal;
}

.cnT {
    font-family: AlimamaShuHeiTi, AlimamaShuHeiTi;
    font-weight: bold;
    font-size: 28rpx;
    color: #ff3b0a;
    line-height: 36rpx;
}

.interest-chart-content {
    z-index: 9;
}
</style>
